#!/bin/bash
# 功能：Java应用镜像构建 → 容器部署 → 旧版本清理
# 用法：./deploy_backend.sh [镜像版本号]

# 参数默认值
IMAGE_VERSION=${1:-1.0}
IMAGE_NAME="backend-app"
CONTAINER_NAME="backend-container"
PORT=8081

# 停止并删除旧容器
clean_old_environment() {
    echo "▸ 清理旧版本容器..."
    if docker stop "$CONTAINER_NAME" >/dev/null 2>&1; then
        docker rm "$CONTAINER_NAME" && echo "✔ 旧容器已移除"
    else
        echo "提示：无运行中的旧容器"
    fi
}

# 删除旧镜像（保留最近2个版本）
prune_old_images() {
    echo "▸ 清理过期镜像..."
    docker images "$IMAGE_NAME" --format "{{.Tag}}" | \
    sort -Vr | \
    tail -n +3 | \
    xargs -I{} docker rmi "$IMAGE_NAME:{}" 2>/dev/null
}

# 构建新镜像
build_new_image() {
    echo "▸ 正在构建镜像 $IMAGE_NAME:$IMAGE_VERSION..."
    if docker build -t "$IMAGE_NAME:$IMAGE_VERSION" . ; then
        echo "✔ 镜像构建成功"
        docker tag "$IMAGE_NAME:$IMAGE_VERSION" "$IMAGE_NAME:latest"
    else
        echo "错误：镜像构建失败（代码：$?）" >&2
        exit 1
    fi
}

# 运行新容器
start_new_container() {
    echo "▸ 启动容器 $CONTAINER_NAME..."
    docker run -d \
        --restart=always \
        --name "$CONTAINER_NAME" \
        -p "$PORT:$PORT" \
        "$IMAGE_NAME:$IMAGE_VERSION"

    # 健康检查
    sleep 2
    if docker ps --filter "name=$CONTAINER_NAME" | grep -q "Up"; then
        echo "✔ 容器已启动，端口映射：$PORT → $PORT"
    else
        echo "错误：容器启动异常" >&2
        docker logs "$CONTAINER_NAME" >&2
        exit 2
    fi
}

# 主流程
clean_old_environment
prune_old_images
build_new_image
start_new_container

echo "✅ 部署完成"